<template>
  <el-form ref="formEl" label-position="top" :model="form" :rules="rules">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="form.username" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="form.password" type="password" />
    </el-form-item>
    <el-form-item label="确认密码" prop="cpassword">
      <el-input v-model="form.cpassword" type="password" />
    </el-form-item>
    <el-form-item label="性别">
      <el-radio-group v-model="form.gender">
        <el-radio label="1">男</el-radio>
        <el-radio label="0">女</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="邮箱" v-model="form.email" prop="email">
      <el-input v-model="form.email" />
    </el-form-item>
    <el-form-item label="手机" v-model="form.phone" prop="phone">
      <el-input v-model="form.phone" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button type="info" link @click="handleCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { addUsersApi, checkUsersExistApi } from '@/api/users';

const emits = defineEmits(['save', 'cancel']);

// 绑定数据
const form = reactive({
  username: '',
  gender: '1',
  email: '',
  phone: '',
  password: '',
  cpassword: '',
});

const formEl = ref(null);

function check(reg, message) {
  return (rule, value, cb) => {
    if (typeof reg === 'function' ? reg(value) : reg.test(value)) {
      cb();
    } else {
      cb(new Error(message));
    }
  };
}

function remoteCheck(field, message) {
  return async (rule, value, cb) => {
    if (value === '') {
      cb();
    } else {
      const res = await checkUsersExistApi(field, value);
      if (res.data) {
        cb(new Error(message));
      } else {
        cb();
      }
    }
  };
}

const emailReg = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
// 验证规则
const rules = reactive({
  username: [
    { required: true, message: '用户名必须填写', trigger: 'change' },
    { validator: check(/^\w{2,18}$/, '用户名2-18位'), trigger: 'change' },
    { validator: remoteCheck('username', '用户名已经存在'), trigger: 'blur' },
  ],
  email: [
    { required: true, message: '邮箱必须填写', trigger: 'change' },
    { validator: check(emailReg, '邮箱格式非法'), trigger: 'change' },
    { validator: remoteCheck('email', '邮箱已经存在'), trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '手机必须填写', trigger: 'change' },
    { validator: check(/^(?:(?:\+|00)86)?1\d{10}$/, '手机格式非法'), trigger: 'change' },
    { validator: remoteCheck('phone', '手机已经存在'), trigger: 'blur' },
  ],
  password: [
    { required: true, message: '密码必须填写', trigger: 'change' },
    { validator: check(/^.{6,18}$/, '密码必须6-18位'), trigger: 'change' },
  ],
  cpassword: [
    {
      validator: check((value) => value === form.password, '两次密码输入不一致'),
      trigger: 'change',
    },
  ],
});

// 保存
async function handleSave() {
  // 表单验证
  await formEl.value.validate();
  // 调用接口
  const fdata = { ...form };
  delete fdata.cpassword;
  await addUsersApi({ ...fdata });
  // 字段重置
  formEl.value.resetFields();
  // 触发保存事件
  emits('save');
}

function handleCancel() {
  // 字段重置
  formEl.value.resetFields();
  // 触发保存事件
  emits('cancel');
}
</script>
